import React, { useEffect, useRef, useState } from 'react';
import Channel from 'components/Channel';
import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Space,
  Upload,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import styles from './index.module.scss';
import { Link, useHistory, useParams } from 'react-router-dom';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { baseURL } from 'utils/request.js';
import { addarticles, getarticlesDetail, editarticles } from 'api/list';
import { Gettoken } from 'utils/localStorage';
export default function ArticlePublish(props) {
  const [btnDisabled, setBtnDisabled] = useState(false);
  const [type, setType] = useState(1);
  const [fileLists, setFileLists] = useState([]);
  const draftRef = useRef(false);
  const FormRef = useRef();
  const [ImgSrc, setImgSrc] = useState('');

  //路由Hooks 的基本使用
  const Params = useParams();
  const History = useHistory();

  //编辑内容回显
  async function getDetail() {
    let { data } = await getarticlesDetail(Params.id);
    FormRef.current.setFieldsValue({
      ...data,
    });
    setType(data.cover.type);
    let list = data.cover.images.map((item) => {
      return { url: item };
    });
    setFileLists(list);
  }

  //页面初始化检测是否为编辑
  useEffect(() => {
    if (Params.id) getDetail();
  }, [Params.id]); // eslint-disable-line react-hooks/exhaustive-deps

  //提交事件
  const onPublished = async (values) => {
    if (type === 1 && fileLists.length !== 1) {
      message.warning('图片数量不正确，请检查');
      return;
    } else if (type === 3 && fileLists.length !== 3) {
      message.warning('图片数量不正确，请检查');
      return;
    }
    let data = {
      ...values,
      cover: {
        type,
        images: [
          ...fileLists.map((item) => item.url || item.response.data.url),
        ],
      },
    };
    if (Params.id) {
      await editarticles(Params.id, draftRef.current, data);
      message.success('编辑文章成功!');
    } else {
      await addarticles(draftRef.current, data);
      message.success('新增文章成功!');
    }
    History.push('/list');
  };

  //计算是否上传图片
  function showAddIcon() {
    if (type === 0) return true;
    if (type === 1 && fileLists.length >= 1) return true;
    if (type === 3 && fileLists.length >= 3) return true;
    return false;
  }

  //单选框选择事件
  const handleRadioFn = (e) => {
    setType(e.target.value);
    if (e.target.value === 0) {
      setFileLists([]);
    } else if (e.target.value === 1 && fileLists.length > 1) {
      setFileLists([JSON.parse(JSON.stringify(fileLists)).shift()]);
    }
  };

  //上传图片改变事件
  const handleUploadChange = ({ file, fileList }) => {
    const { status } = file;
    setFileLists([...fileList]);
    if (status === 'uploading') setBtnDisabled(true);
    if (status === 'done') {
      message.success(`${file.originFileObj.name}上传成功`);
      setBtnDisabled(false);
    }
  };

  //预览图片
  const handlePreview = (file) => {
    setImgSrc(file.url || file.thumbUrl);
  };

  //图片上传前的回调函数
  function beforeUpload(file) {
    const whiteList = ['image/png', 'image/jpg', 'image/jpeg'];
    if (!whiteList.includes(file.type)) {
      message.error('不允许上传的文件类型');
      return Upload.LIST_IGNORE;
    }
  }

  return (
    <Card
      className={styles.publish}
      title={
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to="/home">首页</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            {!Params.id ? '发布文章' : '编辑文章'}
          </Breadcrumb.Item>
        </Breadcrumb>
      }
      bordered={false}
    >
      <Form
        ref={FormRef}
        autoComplete="off"
        size="large"
        onFinish={onPublished}
        initialValues={{
          content: '',
        }}
      >
        <Form.Item
          name="title"
          label="标题"
          rules={[{ required: true, message: '标题不能为空' }]}
        >
          <Input placeholder="请输入文章标题"></Input>
        </Form.Item>

        <Channel rules={[{ required: true, message: '请选择频道' }]}></Channel>

        <Form.Item
          label="内容"
          name="content"
          rules={[
            { required: true, message: '内容不能为空' },
            {
              validator(_, value) {
                if (value === '<p><br></p>') {
                  return Promise.reject('内容不能为空');
                }
                return Promise.resolve('通过');
              },
            },
          ]}
        >
          <ReactQuill placeholder="请输入文章内容..." />
        </Form.Item>

        <Form.Item label="封面">
          <Radio.Group
            name="type"
            defaultValue={1}
            value={type}
            onChange={(e) => handleRadioFn(e)}
            style={{ margin: '10px 0' }}
          >
            <Radio value={1}>一图</Radio>
            <Radio value={3}>三图</Radio>
            <Radio value={0}>无图</Radio>
          </Radio.Group>

          <Upload
            accept=".jpg,.png,.jpeg"
            action={baseURL + '/upload'}
            headers={{
              authorization: `Bearer ${Gettoken()}`,
            }}
            listType="picture-card"
            name="image"
            beforeUpload={beforeUpload}
            onChange={handleUploadChange}
            onPreview={handlePreview}
            fileList={fileLists}
          >
            {!showAddIcon() && <UploadOutlined style={{ fontSize: 30 }} />}
          </Upload>

          <Modal
            visible={!!ImgSrc}
            title="预览图片"
            footer={null}
            maskClosable={false}
            onCancel={() => setImgSrc('')}
          >
            <img style={{ width: '100%' }} src={ImgSrc} alt="预览图片" />
          </Modal>
        </Form.Item>

        <Form.Item>
          <Space>
            <Button
              type="primary"
              htmlType="submit"
              disabled={btnDisabled}
              onClick={() => (draftRef.current = false)}
            >
              {!Params.id ? '发布文章' : '编辑文章'}
            </Button>
            <Button
              disabled={btnDisabled}
              htmlType="submit"
              onClick={() => (draftRef.current = true)}
            >
              存为草稿
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}
